<?php

/*
 *
 *
 *  This software has been made FREE by author for the interest of other developers.
 *       I hope this will help you in coding faster and robust php code
 *             You can modify and redistribute it as you like.
 *               Your comments, suggestions and corrections
 *                           will be highly
 *                            APPRECIATED.
 *                                       Author
 * @author :   Roshan Budhathoki (developer.roshan@gmail.com);
 * @URL    :   <http://www.roshanbudhathoki.com>
 *
 */

class Image_Thumbnail {
	
	//put your code here
	

	private static $instance;
	private $image_resize;
	
	public static function newInstance() {
		if (! self::$instance instanceof self) {
			self::$instance = new self ();
		}
		return self::$instance;
	}
	
	public function __construct() {
		$this->image_resize = new Image_Resize ();
	}
	
	public function resize($width, $height, $path) {
		$this->image_resize->load ( $path );
		return $this->getImage ( $path, $width, $height );
	}
	
	public function getImage($file, $width, $height) {
		
		$ext = pathinfo ( $file );
		$ext = $ext ['extension'];
		
		$filename = substr ( $file, strrpos ( $file, DS ) + 1, - 4 );
		$o_filename = $filename . '.' . $ext;
		$filename = $filename . '_' . $width . 'x' . $height . '.' . $ext;
		
		//        $path = APP_PATH . 'cache' . DS . 'images' . DS;
		

		$path = str_replace ( $o_filename, '', $file );
		
		if (! is_dir ( $path . 'cache' . DS )) {
			mkdir ( $path . 'cache' . DS, 0755 );
		}
		
		$section_path = str_replace ( content_path(), '', $path );
		
		$parts = explode ( DS, $section_path );
		$section_url = content_url(). implode ( '/', $parts ) . 'cache/';
		
		// echo $filename;
		$file_path = $path . 'cache' . DS . $filename;
		$file_uri = $section_url . $filename;
		$args = array ('path' => $file_path, 'uri' => $file_uri );
		if (! file_exists ( $file_path )) {
			if ($width > $height) {
				$this->image_resize->resizeToHeight ( $height );
			} else {
				
				$this->image_resize->resizeToWidth ( $width );
			}
			
			$this->image_resize->save ( $file_path );
		}
		
		return new Image_Image ( $args );
	}

}
